/** * 客户表单组件 - 用于创建和编辑客户信息 * @author songxinfeng * @date 2024-12-27 */
<template>
  <div class="customer-form-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑客户' : '创建客户' }}</span>
          <div class="header-buttons">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        label-width="120px"
        class="customer-form"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="formState.name" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户阶段" prop="stage">
              <el-select v-model="formState.stage" placeholder="请选择客户阶段" class="w-full">
                <el-option
                  v-for="stage in customerStages"
                  :key="stage.value"
                  :label="stage.label"
                  :value="stage.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户来源" prop="source">
              <el-select v-model="formState.source" placeholder="请选择客户来源" class="w-full">
                <el-option
                  v-for="source in customerSources"
                  :key="source.value"
                  :label="source.label"
                  :value="source.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industryId">
              <el-select v-model="formState.industryId" placeholder="请选择所属行业" class="w-full">
                <el-option
                  v-for="industry in industries"
                  :key="industry.id"
                  :label="industry.name"
                  :value="industry.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系信息 -->
        <el-divider content-position="left">联系信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="formState.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formState.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="formState.contactEmail" placeholder="请输入联系邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人职位" prop="contactPosition">
              <el-input v-model="formState.contactPosition" placeholder="请输入联系人职位" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 公司信息 -->
        <el-divider content-position="left">公司信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司网站" prop="website">
              <el-input v-model="formState.website" placeholder="请输入公司网站" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照号" prop="businessLicense">
              <el-input v-model="formState.businessLicense" placeholder="请输入营业执照号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年营业额" prop="annualRevenue">
              <el-input-number
                v-model="formState.annualRevenue"
                :min="0"
                :precision="2"
                :step="10000"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工人数" prop="employeeCount">
              <el-input-number
                v-model="formState.employeeCount"
                :min="0"
                :step="10"
                class="w-full"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 地址信息 -->
        <el-divider content-position="left">地址信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拜访地址" prop="visitAddress">
              <el-input v-model="formState.visitAddress" placeholder="请输入拜访地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册地址" prop="registerAddress">
              <el-input v-model="formState.registerAddress" placeholder="请输入注册地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息 -->
        <el-divider content-position="left">备注信息</el-divider>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formState.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { createCustomer, updateCustomer, getCustomer } from '@/api/customer'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const isEdit = ref(false)

interface Industry {
  id: number
  name: string
}

const industries = ref<Industry[]>([])

const formState = reactive({
  name: '',
  stage: '',
  source: '',
  industryId: null as number | null,
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  contactPosition: '',
  website: '',
  businessLicense: '',
  annualRevenue: 0,
  employeeCount: 0,
  visitAddress: '',
  registerAddress: '',
  remark: '',
})

const rules = {
  name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  stage: [{ required: true, message: '请选择客户阶段', trigger: 'change' }],
  source: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
  contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
}

const customerStages = [
  { value: 'LEAD', label: '潜在客户' },
  { value: 'QUALIFIED', label: '已确认需求' },
  { value: 'PROPOSAL', label: '方案报价' },
  { value: 'NEGOTIATION', label: '商务谈判' },
  { value: 'CONTRACT', label: '合同签订' },
  { value: 'IMPLEMENTATION', label: '实施交付' },
  { value: 'MAINTENANCE', label: '售后维护' },
  { value: 'LOST', label: '已流失' },
]

const customerSources = [
  { value: 'TELEMARKETING', label: '电话营销' },
  { value: 'WEBSITE', label: '官网' },
  { value: 'SOCIAL_MEDIA', label: '社交媒体' },
  { value: 'REFERRAL', label: '客户推荐' },
  { value: 'EXHIBITION', label: '展会' },
  { value: 'SEARCH_ENGINE', label: '搜索引擎' },
  { value: 'EMAIL_MARKETING', label: '邮件营销' },
  { value: 'PARTNER', label: '合作伙伴' },
  { value: 'OTHER', label: '其他' },
]

// 加载行业分类列表
const loadIndustries = async () => {
  try {
    const response = await axios.get('/api/industries')
    industries.value = response.data
    console.log('行业分类加载成功:', response.data)
  } catch (error) {
    console.error('获取行业分类失败:', error)
    ElMessage.error('获取行业分类失败')
  }
}

// 加载客户数据（编辑时使用）
const loadCustomerData = async (id: number) => {
  try {
    const response = await getCustomer(id)
    const customerData = response.data

    // 确保 industryId 正确赋值
    Object.assign(formState, {
      ...customerData,
      industryId: customerData.industryId || null,
    })

    console.log('客户数据加载成功:', customerData)
    console.log('行业ID:', customerData.industryId)
  } catch (error) {
    console.error('获取客户信息失败:', error)
    ElMessage.error('获取客户信息失败')
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateCustomer(Number(route.params.id), formState)
          // 记录编辑日志
          await axios.post('/api/logs', {
            action: 'UPDATE_CUSTOMER',
            description: `更新客户：${formState.name}`,
          })
          ElMessage.success('更新成功')
        } else {
          await createCustomer(formState)
          // 记录创建日志
          await axios.post('/api/logs', {
            action: 'CREATE_CUSTOMER',
            description: `创建客户：${formState.name}`,
          })
          ElMessage.success('创建成功')
        }
        router.push('/customers')
      } catch (error) {
        console.error('保存客户失败:', error)
        ElMessage.error('保存客户失败')
      }
    }
  })
}

const handleCancel = () => {
  router.push('/customers')
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: isEdit.value ? '访问编辑客户页面' : '访问创建客户页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

onMounted(async () => {
  // 先加载行业分类数据
  await loadIndustries()

  const id = route.params.id
  if (id) {
    isEdit.value = true
    // 行业分类加载完成后再加载客户数据，确保回显正常
    await loadCustomerData(Number(id))
  }

  recordPageAccess()
})
</script>

<style scoped>
.customer-form-container {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.customer-form {
  margin-top: 20px;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
}

.w-full {
  width: 100%;
}
</style>
